package com.s59.rabc.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.s59.rabc.commen.LoginException;
import com.s59.rabc.entity.Menu;
import com.s59.rabc.entity.Role;
import com.s59.rabc.entity.User;
import com.s59.rabc.security.UserDetailsimpl;
import com.s59.rabc.service.IMenuService;
import com.s59.rabc.service.IRoleService;
import com.s59.rabc.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PermssionService implements UserDetailsService {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IUserService userService;

    public Set<String> getRoleKey(String userName){
        return roleService.getByUserName(userName).stream().map(Role::getRoleKey).collect(Collectors.toSet());
    }

    public Set<String> getParms(String userName){
        List<Role> roleList = roleService.getByUserName(userName);
        List<Menu> menuList = menuService.getByRoleIdList(roleList.stream().mapToLong(Role::getRoleId).boxed().collect(Collectors.toList()));
        return menuList.stream()
                .filter(item -> StringUtils.hasText(item.getPerms()))
                .map(Menu::getPerms).collect(Collectors.toSet());
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,s));
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        UserDetailsimpl userDetails = new UserDetailsimpl();
        userDetails.setUsername(user.getUserName());
        userDetails.setNickname(user.getNickName());
        userDetails.setPassword(user.getPassword());
        Set<String> parms = this.getParms(user.getUserName());
        Set<String> roleKey = this.getRoleKey(user.getUserName());
        userDetails.setRoleNames(parms);
        userDetails.setPermsList(roleKey);
        return userDetails;
    }
}
